#include "MyCSVReader.h"
#include <QFileDialog>
#include <QtCore/QCoreApplication>
#include <QTextStream>
#include <QDebug>

MyCSVReader::MyCSVReader(QObject *parent) : QObject(parent)
{

}

MyCSVReader::~MyCSVReader()
{
    if(CSVFile.isOpen()) CSVFile.close();
}

QVector<QStringList> MyCSVReader::GetDataFromCSVFile()
{
    QVector<QStringList> OutputBuffer;
    OutputBuffer.clear();
    QStringList list;
    list.clear();

    if(prvOpenFile()){
        QTextStream in(&CSVFile);
        in.setCodec("GB2312");
        for(int i = 0;!in.atEnd();i++){
            QString fileLine = in.readLine();
            list = fileLine.split(",", QString::SkipEmptyParts);
            OutputBuffer.append(list);
        }
        CSVFile.close();
    }
    return OutputBuffer;
}

QVector<QStringList> MyCSVReader::GetDataFromCSVFile(QString FileName)
{
    QVector<QStringList> OutputBuffer;
    OutputBuffer.clear();
    QStringList list;
    list.clear();

    if(prvOpenFile(FileName)){
        QTextStream in(&CSVFile);
        in.setCodec("GB2312");
        for(int i = 0;!in.atEnd();i++){
            QString fileLine = in.readLine();
            list = fileLine.split(",", QString::SkipEmptyParts);
            OutputBuffer.append(list);
        }
        CSVFile.close();
    }
    return OutputBuffer;
}

bool MyCSVReader::prvOpenFile()
{
    QString FileName = QFileDialog::getOpenFileName(nullptr, tr("Excel file"), qApp->applicationDirPath(), tr("Files (*.csv)"));
    CSVFile.setFileName(FileName);
    return CSVFile.open(QIODevice::ReadOnly | QIODevice::Text);
}

bool MyCSVReader::prvOpenFile(QString FileName)
{
    CSVFile.setFileName(FileName);
    return CSVFile.open(QIODevice::ReadOnly | QIODevice::Text);
}
